import React, {useEffect, useState} from "react";
import './personal-info.scss'
import {Avatar, Button, Modal, Form, Input, Select, Upload, message, Image} from 'antd';
import {UserOutlined, AntDesignOutlined, UploadOutlined, EyeOutlined} from '@ant-design/icons';
import {getFormDistrictInfo} from "../../../api/districtApi";
import {getUserExtendMsg} from "../../../api/userApi";
import {uploadFile} from "../../../api/attachmentApi";
import {addUserExtendMsg} from "../../../api/userExtendMsgApi";
import {
    addUserDistrictWithDistrictIds,
    addUserDistrict,
    deleteUserDistrict,
    queryUserDistrict,
} from "../../../api/userDistrictApi";
import UploadFile from "../../upload_file/UploadFile";

function PersonalInfo(props) {
    //模拟用户id
    const userId = JSON.parse(localStorage.getItem("data")).userId;
    const {Option} = Select;
    const [visible, setVisible] = useState(false);
    const [fileList, setFileList] = useState([]);
    const [districtOption, setDistrictOption] = useState([]);
    const [userExtendMsg, setUserExtendMsg] = useState({});
    const [userDistrictList, setUserDistrictList] = useState([]);
    const [hasSubmitted, setHasSubmitted] = useState(false);

    useEffect(() => {
        getDistrictInfo(1);

        //获取用户的扩展信息
        getUserExtendMsg(userId).then(resp => {
            setUserExtendMsg(resp);
        });

        queryUserDistrict(userId).then(r => {
            const userDistrictList = [];
            for (let i in r) {
                userDistrictList.push(r[i].id.toString());
            }
            setUserDistrictList(userDistrictList);
        });
    }, []);

    const showModal = () => {
        setVisible(true);
    }

    const getDistrictInfo = (parentId) => {
        getFormDistrictInfo(parentId).then(resp => {
            const districtList = resp;
            const districtOption = [];
            for (let i in districtList) {
                const district = districtList[i];
                districtOption.push(<Option key={district.id}>{district.name}</Option>);
            }
            setDistrictOption(districtOption);
        })
    }

    const handleCancel = () => {
        setVisible(false);
    }

    const layout = {
        labelCol: {
            span: 8,
        },
        wrapperCol: {
            span: 16,
        },
    };

    const onFinish = (values) => {
        const unit = values.unit;
        if (unit.name === undefined) {
            message.error("单位名称不能为空").then(() => {
            });
            return;
        }
        if (unit.address === undefined) {
            message.error("单位地址不能为空").then(() => {
            });
            return;
        }
        if (unit["businessLicense"] === undefined) {
            message.error("请上传营业执照").then(() => {
            });
            return;
        }

        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('files', file);
        });

        let uploadResult = null;
        const uri = {tableName: "UserExtendMsg", fieldName: "BusinessLicense", ownerId: 0}

        setVisible(false);
        setHasSubmitted(true);

        uploadFile(uri, formData).then(resp => {
            uploadResult = resp;
            setFileList([]);

            //获取返回的id值
            let attachmentId = uploadResult["data"][0];

            //添加用户扩展信息
            const userExtendMsg = {userId: userId, orgName: unit.name, orgAddress: unit.address}
            addUserExtendMsg(attachmentId, userExtendMsg).then(() => {
                setHasSubmitted(false);
            }).catch(() => {
                const districtIds = unit["district"];
                if (districtIds !== undefined) {
                    //停车场区域不为空时，添加用户区域信息
                    addUserDistrictWithDistrictIds(userId, districtIds).then(() => {
                        window.location.href = "../personal?menu=personal";
                    }).catch(() => {
                        window.location.href = "../personal?menu=personal";
                    })
                }
                window.location.href = "../personal?menu=personal";
            });
        }).catch(resp => {
            message.error("文件上传失败，请稍后重试").then(() => {
            });
            uploadResult = resp;
            setHasSubmitted(false);
        });
    }

    const handleSelect = (value) => {
        setUserDistrictList([...userDistrictList, value]);
        const userDistrict = {
            districtId: value,
            userId,
        }
        addUserDistrict(userDistrict);
    }

    const handleDeselect = (value) => {
        const i = userDistrictList.indexOf(value);
        userDistrictList.splice(i, 1);
        setUserDistrictList([...userDistrictList]);

        const districtIds = [value];
        deleteUserDistrict(userId, districtIds);
    }

    const handleClear = () => {
        setUserDistrictList([]);
        deleteUserDistrict(userId, userDistrictList);
    }

    // const uploadProps = {
    //     maxCount: 1,
    //     onRemove: file => {
    //         const index = fileList.indexOf(file);
    //         const newFileList = fileList.slice();
    //         newFileList.splice(index, 1);
    //         setFileList(newFileList);
    //     },
    //     beforeUpload: file => {
    //         const patter = /image/;
    //         if (patter.test(file.type)) {
    //             setFileList([file]);
    //         } else {
    //             message.error("请上传图片文件").then(() => {
    //             });
    //         }
    //         return false;
    //     },
    //     fileList,
    // };

    return (
        <div>
            <div style={{display: userExtendMsg ? "none" : "block"}}>
                <div className={'personal-info-container'}>
                    <Avatar size={64} icon={<UserOutlined/>}/>
                    <div className={'personal-info-detail'}>
                        单位名称、营业执照绑定后不可修改，若要更换单位和营业执照请重新注册账号，再绑定停车场
                    </div>
                    <Button type={'primary'} onClick={showModal} loading={hasSubmitted}>完善单位信息</Button>

                    <Modal
                        title="完善单位信息"
                        visible={visible}
                        onCancel={handleCancel}
                        footer={null}
                    >
                        <Form {...layout} name="nest-messages"
                              onFinish={onFinish}
                              labelAlign={"left"}
                        >
                            <Form.Item
                                name={['unit', 'name']}
                                label="单位名称"
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name={['unit', 'address']}
                                label="单位地址"
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name={['unit', 'businessLicense']}
                                label="营业执照"
                            >
                                {/*<Upload {...uploadProps}>*/}
                                {/*    <Button icon={<UploadOutlined/>}>选择文件</Button>*/}
                                {/*</Upload>*/}
                                <UploadFile fileList={fileList} setFileList={setFileList}/>
                            </Form.Item>

                            <Form.Item name={['unit', 'district']}
                                       label="停车场所在区域"
                            >
                                <Select
                                    mode="multiple"
                                    allowClear
                                    style={{width: '100%'}}
                                >
                                    {districtOption}
                                </Select>
                            </Form.Item>

                            <Form.Item wrapperCol={{...layout.wrapperCol, offset: 8}}>
                                <div id={"finish-unit-info-footer"}>
                                    <Button className={"finish-unit-info-footer-button"}
                                            onClick={handleCancel}
                                    >
                                        取消
                                    </Button>

                                    <Button className={"finish-unit-info-footer-button"}
                                            type="primary"
                                            htmlType="submit"
                                    >
                                        提交
                                    </Button>
                                </div>
                            </Form.Item>
                        </Form>
                    </Modal>
                </div>
            </div>

            <div className={"user-finished-info"} style={{display: userExtendMsg ? "block" : "none"}}>
                <div className={"content"}>
                    <div className="user-photo">
                        <Avatar
                            size={{xs: 32, sm: 40, md: 64, lg: 100, xl: 150, xxl: 200}}
                            icon={<AntDesignOutlined/>}
                        />
                        <p className={"user-photo-tip"}>
                            单位名称、营业执照绑定后不可修改，若需要更换单位和营业执照请重新注册账号，再绑定停车场
                        </p>
                    </div>
                    <div className="user-info">
                        <table>
                            <tbody>
                            <tr>
                                <td>单位名称：</td>
                                <td className={"col-2"}>{userExtendMsg.orgName}</td>
                            </tr>

                            <tr>
                                <td>单位地址：</td>
                                <td className={"col-2"}>{userExtendMsg.orgAddress}</td>
                            </tr>

                            <tr>
                                <td style={{verticalAlign: "top"}}>营业执照：</td>
                                <td className={"col-2"}>
                                    <Image
                                        width={200}
                                        src={userExtendMsg.filePath}
                                        preview={{mask: <div><EyeOutlined/> 预览</div>}}
                                    />
                                </td>
                            </tr>

                            <tr>
                                <td>停车场所在区域：</td>
                                <td className={"col-2"}>
                                    <Select
                                        mode="multiple"
                                        allowClear
                                        style={{width: '100%'}}
                                        onSelect={handleSelect}
                                        onDeselect={handleDeselect}
                                        onClear={handleClear}
                                        value={userDistrictList}
                                        size={"middle"}
                                    >
                                        {districtOption}
                                        {[...userDistrictList]}
                                    </Select>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default PersonalInfo;